var Consts = require('../../../util/consts');
var killerUserDao = require('../../../dao/killer/killerUserDao');
var killerRoomDao = require('../../../dao/killer/killerRoomDao');
var messageService = require('../../../services/messageService');

module.exports = function (app) {
    return new ReconnectHandler(app);
};

var admin = 'backgroundAdmin';


var ReconnectHandler = function (app) {
    this.app = app;
};
var handler = ReconnectHandler.prototype;

/**
 * reconnect when error happened
 * @param msg
 * @param session
 * @param next
 */
handler.reconnect = function (msg, session, next) {
    var username = msg.username;
    var rid = session.get('rid');
    var self = this;
    killerUserDao.getUserByID(username, rid, function (err, user) {
        if (user.isConfirm) {
            next(null, {code: 200, action: Consts.KillerAction.START_SEEK});
        } else if (user.isConfirm === false) {
            next(null, {code: 200, action: Consts.KillerAction.GAME_OVER});
        } else {
            var route = Consts.GameRoute.KILLER_GAME;
            messageService.getLatestMessage(route, admin, rid, function (err, message) {
                if (err) {
                    next(null, {code: 400, action: 'notPermitted'});
                } else {
                    messageService.send(admin, username, message.content, rid, route, self.app);
                    next(null, {code: 200, action: 'otherActions'});
                }
            });

        }
    });

};

handler.recover = function(msg, session, next) {
    var username = msg.username;
    var rid = session.get('rid');
    var tid = msg.tid;
    if (!username || !rid || tid == null) {
        next(null, {code: 400});
        return;
    }
    var self = this;
    messageService.getMessagesAfterTid(username, rid, tid, function (err, messages) {
        killerUserDao.getUserByID(username, rid, function (err, user) {
            killerRoomDao.getRoom(rid, function (err, room) {
                next(null, {code: 200, status: user.isLive, gameStatus: room.state, msg: messages});
            });
        });
    });
};

